package wc

import (
	"fmt"
	"io/ioutil"
	"main/env"
	"main/protos"
	"net/http"
	"net/url"
	"regexp"
)

func DoAuth(unionId string) string {
	var params = url.Values{}
	params.Add("union_id", unionId)
	resp, err := http.Get(fmt.Sprintf("http://%s/auth?%s", env.AuthServer, params.Encode()))
	if err != nil {
		return err.Error()
	}

	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err.Error()
	}

	var bm protos.BaseMessage

	err = bm.XXX_Unmarshal(content)
	if err != nil {
		return err.Error()
	}

	var httpreq = regexp.MustCompile(`http.*`)
	if httpreq.Match(bm.Data) {
		return fmt.Sprintf(`<a href ="%s">点我绑定</a>`, string(bm.Data))
	} else {
		return string(bm.Data)
	}

}

func Unbind(unionId string) string {
	var params = url.Values{}
	params.Add("union_id", unionId)
	params.Add("func", "unbind")
	resp, err := http.Get(fmt.Sprintf("http://%s/func?%s", env.AuthServer, params.Encode()))
	if err != nil {
		return err.Error()
	}
	defer resp.Body.Close()
	content, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return err.Error()
	}

	var bm protos.BaseMessage

	err = bm.XXX_Unmarshal(content)
	if err != nil {
		return err.Error()
	}
	return string(bm.Data)
}
